package com.meida.archive.admin.listener;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.meida.module.arc.client.entity.ArcInfoRemind;
import com.meida.module.arc.provider.service.ArcInfoRemindService;
import com.meida.module.arc.provider.service.ArcUseRemindService;
import com.meida.module.system.provider.service.SysExpireStrategyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class RemindRedisKeyExpireListener extends KeyExpirationEventMessageListener {


    @Autowired
    private SysExpireStrategyService sysExpireStrategyService;
    @Autowired
    private ArcInfoRemindService arcInfoRemindService;
    @Autowired
    private ArcUseRemindService arcUseRemindService;


    public RemindRedisKeyExpireListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String redisKey = new String(message.getBody());
        String key = new String(message.getBody());
        String prefix = "infoRemind";

        if (key.contains(prefix)) {
            log.info("档案提醒redis过期key监听" + key);
            Long id = Long.valueOf(key.split(":")[1]);
            try {
                ArcInfoRemind infoRemind = arcInfoRemindService.getById(id);

                if (ObjectUtil.isNotNull(infoRemind) && StrUtil.isNotEmpty(infoRemind.getRemindUserIds())) {
                    for (String s : StrUtil.split(infoRemind.getRemindUserIds(), ",")) {
                        arcUseRemindService.createRemid(5, "档案到期提醒", infoRemind.getQzId(), Long.valueOf(s), infoRemind.getCategoryId(), infoRemind.getArcInfoId());
                    }
                }
                sysExpireStrategyService.deleteByRedisKey(redisKey);

            } catch (Exception e) {
                log.error("档案提醒异常", e);
            }

        }

    }
}
